package auth

import (
	"fmt"
	"github.com/go-resty/resty/v2"
)

type AuthClient struct {
	ClientID     string
	ClientSecret string
	TokenURL     string
	RefreshToken string
	Scope        string
}

type TokenResponse struct {
	AccessToken  string `json:"access_token"`
	TokenType    string `json:"token_type"`
	ExpiresIn    int64  `json:"expires_in"`
	RefreshToken string `json:"refresh_token"`
}

// GetAccessToken retrieves an LWA access token using refresh_token
func (ac *AuthClient) GetAccessToken(RefreshToken string) (TokenResponse, error) {
	client := resty.New()
	resp := TokenResponse{}
	// Send POST request to get token
	_, err := client.R().
		SetHeader("Content-Type", "application/x-www-form-urlencoded").
		SetFormData(map[string]string{
			"grant_type":    "refresh_token",
			"client_id":     ac.ClientID,
			"client_secret": ac.ClientSecret,
			"refresh_token": RefreshToken,
		}).
		SetResult(&resp).
		Post(ac.TokenURL)
	if resp.AccessToken == "" {
		return resp, fmt.Errorf("AccessToken is empty")
	}
	if err != nil {
		return resp, fmt.Errorf("failed to get access token: %w", err)
	}
	return resp, nil
}

/**
 * 生成授权码
 * @param scope sellingpartnerapi::notifications || sellingpartnerapi::client_credential:rotation
 * @return
 */
func (ac *AuthClient) GetGrantlessAccessToken(scope string) (TokenResponse, error) {
	client := resty.New()
	resp := TokenResponse{}
	_, err := client.R().
		SetHeader("Content-Type", "application/x-www-form-urlencoded").
		SetFormData(map[string]string{
			"grant_type":    "client_credentials",
			"client_id":     ac.ClientID,
			"client_secret": ac.ClientSecret,
			"scope":         scope,
		}).
		SetResult(&resp).
		Post(ac.TokenURL)
	if err != nil {
		return resp, fmt.Errorf("failed to get grantless access token: %w", err)
	}
	if resp.AccessToken == "" {
		return resp, fmt.Errorf("AccessToken is empty")
	}
	return resp, nil
}
